package com.zmn.oms.dubbo.impl.zmn.shop.order;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.zmn.base.price.common.dto.ProductPriceDRO;
import com.zmn.base.price.common.dto.item.ItemDRO;
import com.zmn.base.product.common.dto.product.ProductBaseQuery;
import com.zmn.base.product.common.dto.product.ec.ProductBaseDRO;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductForeignListRemoteService;
import com.zmn.common.constant.FicoConsts;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.math.MathUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.validator.ValidateResult;
import com.zmn.common.utils.validator.ValidatorUtil;
import com.zmn.dms.common.dto.preferential.dro.PromBaseRuleDRO;
import com.zmn.dms.dubbo.interfaces.activity.ActivityInfoListRemoteService;
import com.zmn.oms.business.interfaces.es.OrderWorkEsBService;
import com.zmn.oms.business.interfaces.log.OrderQuotationLogBService;
import com.zmn.oms.business.interfaces.orderamount.OrderAmountBService;
import com.zmn.oms.business.interfaces.orderamount.OrderDiscountCalcBService;
import com.zmn.oms.common.constant.OmsErrorCodeConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.dubbo.dto.zmn.order.CancelOrderDIO;
import com.zmn.oms.dubbo.dto.zmn.order.NewOrderDRO;
import com.zmn.oms.dubbo.dto.zmn.order.OrderDiscountDIO;
import com.zmn.oms.dubbo.dto.zmn.order.shop.*;
import com.zmn.oms.dubbo.dto.zmn.serviceitem.OrderServiceItemDIO;
import com.zmn.oms.dubbo.impl.zmn.order.OrderWorkBaseRemoteService;
import com.zmn.oms.dubbo.interfaces.zmn.shop.order.ShopOrderWorkRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.bo.orderamount.CalcAddOrderAmountDIO;
import com.zmn.oms.model.bo.orderamount.DiscountConditionParamsDIO;
import com.zmn.oms.model.bo.orderamount.OrderAmountDIO;
import com.zmn.oms.model.bo.orderamount.OrderDiscountCalcBO;
import com.zmn.oms.model.dto.order.zmn.ZsNormalNewOrderDTO;
import com.zmn.oms.model.dto.orderamount.DiscountCalculateResultDTO;
import com.zmn.oms.model.dto.orderamount.DiscountDTO;
import com.zmn.oms.model.dto.work.masterwork.ModifyQuotationDTO;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.log.OrderQuotationLog;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.work.OperatePermissionVO;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import com.zmn.ums.common.constant.UserConsts;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;

import java.util.*;

/**
 * 类描述：店铺工单
 * @author heciqi
 * @date 2019/08/21 18:25
 */
@Service(loadbalance = "roundrobin", timeout = 20000, retries = 2, version = DubboConsts.INTERFACE_VERSION)
public class ShopOrderWorkRemoteServiceImpl extends OrderWorkBaseRemoteService implements ShopOrderWorkRemoteService {

	static final String TAG = "SAAS-店铺单";

	@Autowired
	private OrderAmountBService orderAmountBService;

	@Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
	private ProductForeignListRemoteService productForeignListRemoteService;
	@Reference(version = com.zmn.dms.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
	private ActivityInfoListRemoteService activityInfoListRemoteService;

	@Autowired
	private OrderDiscountCalcBService orderDiscountCalcBService;
	@Autowired
	private OrderWorkEsBService orderWorkEsBService;
	@Autowired
	private OrderQuotationLogBService orderQuotationLogBService;
	@Autowired
	private ZsOrderWorkOperatePermissionBService orderWorkOperatePermissionBService;

	/**
	 * 获取工单量
	 *
	 * @return
	 */
	@Override
	public ResponseDTO<Integer> getOrderCount() {
		BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
				.mustNot(QueryBuilders.termQuery("type", OrderConsts.ORDER_TYPE_REFUND));
		NativeSearchQuery searchQuery = new NativeSearchQuery(queryBuilder);
		int count = orderWorkEsBService.countByQuery(searchQuery).intValue();
		return ResponseDTO.success(count);
	}

	/**
	 * 获取订单金额
	 *
	 * @param orderAmountByCalcDIO
	 * @return
	 */
	@Override
	public ResponseDTO<OrderAmountByCalcDRO> getOrderAmountByCalc(OrderAmountByCalcDIO orderAmountByCalcDIO) {
		logger.info("[{}] 获取订单价格-请求：getOrderAmountByCalc={}", TAG, JSON.toJSONString(orderAmountByCalcDIO));
		ValidateResult validateResult = ValidatorUtil.validator(orderAmountByCalcDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseDTO.fail("提交参数错误：" + validateResult.toString());
		}

		ResponseDTO<ProductPriceDRO> ResponseProductPriceDRO = orderAmountBService.getProductPriceDRO(orderAmountByCalcDIO.getCityId(), orderAmountByCalcDIO.getChannelId(), orderAmountByCalcDIO.getShowProductId());
		if (!ResponseProductPriceDRO.isSuccess()) {
			return ResponseDTO.fail(ResponseProductPriceDRO.getMessage());
		}

		// 无产品价格
		ProductPriceDRO productPriceDRO = ResponseProductPriceDRO.getData();
		if (productPriceDRO == null) {
			return ResponseDTO.success(
					OrderAmountByCalcDRO.builder()
							.haveAmount(GlobalConsts.NO).build()
			);
		}

		// 获取支付金额
		Integer payAmount = orderAmountBService.getPayAmount(productPriceDRO, 1);
		Integer discountAmount = null;
		List<DiscountDTO> list = Lists.newArrayList();
		// 优惠处理
		if (NumberUtil.isNotNullOrZero(payAmount)) {
			try {
				// 优惠券优惠
				DiscountDTO couponDiscount = orderAmountBService.getCouponDiscount(orderAmountByCalcDIO.getCityId(), orderAmountByCalcDIO.getChannelId(),
						orderAmountByCalcDIO.getShowProductId(), orderAmountByCalcDIO.getUserId(), orderAmountByCalcDIO.getItemCode(), payAmount);
				if (couponDiscount != null) {
					list.add(couponDiscount);
				}
				// 一口价优惠
				if (Objects.equals(orderAmountByCalcDIO.getUsePayDiscount(), GlobalConsts.YES)) {
					DiscountDTO finalPriceDiscount = orderAmountBService.getFinalPriceDiscount(productPriceDRO);
					if (finalPriceDiscount != null) {
						list.add(finalPriceDiscount);
					}
				}
			} catch (OmsBaseException e) {
				return ResponseDTO.fail(e.getMessage());
			}
			// 计算优惠
			DiscountCalculateResultDTO discountCalculateResultDTO = orderAmountBService.calculateDiscount(list, payAmount);
			if (discountCalculateResultDTO != null) {
				payAmount = discountCalculateResultDTO.getAfterDiscountAmount();
				discountAmount = discountCalculateResultDTO.getDiscountAmount();
			}
		}

		OrderAmountByCalcDRO orderAmountByCalcDRO = new OrderAmountByCalcDRO();
		orderAmountByCalcDRO.setHaveAmount(GlobalConsts.YES);
		orderAmountByCalcDRO.setOriginalAmount(productPriceDRO.getPrice());
		orderAmountByCalcDRO.setPayAmount(payAmount);
		orderAmountByCalcDRO.setDiscountAmount(discountAmount);
		orderAmountByCalcDRO.setPrepayType(Optional.ofNullable(productPriceDRO.getPayType()).orElse(2));// 默认下单后支付
		orderAmountByCalcDRO.setFinalPrice(Objects.equals(productPriceDRO.getItemStandard(), GlobalConsts.YES) ? GlobalConsts.YES : GlobalConsts.NO);
		orderAmountByCalcDRO.setOrderServiceItemList(Lists.newArrayList(this.convertToServiceItemDIO(productPriceDRO.getItemDRO())));
		orderAmountByCalcDRO.setOrderDiscountList(this.convertToDiscountDIO(list));
		logger.info("[{}] 获取订单价格-返回：getOrderAmountByCalc={}", TAG, orderAmountByCalcDRO);
		return ResponseDTO.success(orderAmountByCalcDRO);
	}

	@Override
	public ResponseDTO<Boolean> checkOrderProductNumber(CheckOrderProductNumberDIO productNumberDIO) {
        logger.info("#oms#用户id={}，校验订单产品数量-请求：checkOrderProductNumber={}", productNumberDIO.getUserId(), JSON.toJSONString(productNumberDIO));
		// 1，产品数量为1直接返回成功
		if (Objects.equals(productNumberDIO.getNumber(), GlobalConsts.NO)) {
			return ResponseDTO.success(true);
		}

		// 2，计价器-->只能有一个产品数量
		if (Objects.equals(productNumberDIO.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_FAULT)) {
			return ResponseDTO.success(false);
		}

		// 3，前台产品--若映射多个后台产品-->只能有一个产品数量
		ProductBaseQuery query = new ProductBaseQuery();
		// query.setCityId(cityId);
		query.setProductId(productNumberDIO.getShowProductId());
		query.setChannelId(productNumberDIO.getChannelId());
		query.setBizType(productNumberDIO.getBizType());
		query.setStatus(GlobalConsts.YES);
		query.setNeedPriceMsg(true);
		logger.info("#oms#--->用户id={}，listBaseDROByDIO 入参：{}", productNumberDIO.getUserId(), JSON.toJSONString(query));
		ResponseDTO<List<ProductBaseDRO>> responseDTO = productForeignListRemoteService.listBaseDROByQuery(query);
		logger.info("#oms#--->用户id={}，listBaseDROByDIO 出参：{}", productNumberDIO.getUserId(), JSON.toJSONString(responseDTO));
		List<ProductBaseDRO> productBaseDRO = responseDTO.getData();
		if (!responseDTO.isSuccess() || CollectionUtil.isNullOrEmpty(productBaseDRO)) {
			return ResponseDTO.success(false);
		}

		return ResponseDTO.success(Objects.equals(productBaseDRO.size(), 1));
	}

    /**
	 * 计算订单金额
	 *
	 * @param calcOrderAmountDIO
	 * @return
	 */
	@Override
	public ResponseDTO<CalcOrderAmountDRO> calcOrderAmount(CalcOrderAmountDIO calcOrderAmountDIO) {
		logger.info("[{}] 获取订单价格-请求：calcOrderAmount={}", TAG, JSON.toJSONString(calcOrderAmountDIO));
		ValidateResult validateResult = ValidatorUtil.validator(calcOrderAmountDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseDTO.fail("提交参数错误：" + validateResult.toString());
		}

		ResponseDTO<ProductPriceDRO> ResponseProductPriceDRO = orderAmountBService.getProductPriceDRO(calcOrderAmountDIO.getCityId(), calcOrderAmountDIO.getChannelId(), calcOrderAmountDIO.getShowProductId());
		if (!ResponseProductPriceDRO.isSuccess()) {
			return ResponseDTO.fail(ResponseProductPriceDRO.getMessage());
		}

		// 无产品价格
		ProductPriceDRO productPriceDRO = ResponseProductPriceDRO.getData();
		if (productPriceDRO == null) {
			return ResponseDTO.success(
					CalcOrderAmountDRO.builder()
							.haveAmount(GlobalConsts.NO).build()
			);
		}

		// 产品数量
		Integer number = Optional.ofNullable(calcOrderAmountDIO.getNumber()).orElse(1);
		// 获取支付金额
		Integer payAmount = orderAmountBService.getPayAmount(productPriceDRO, number);
		Integer discountAmount = null;
		List<DiscountDTO> list = Lists.newArrayList();
		List<OrderDiscount> orderDiscountList = Lists.newArrayList();
		List<Set<CalcOrderAmountPromBaseRuleDRO>> linkOfValidAll = Lists.newArrayList();
		boolean isEarnestPrice = NumberUtil.isNotNullOrZero(productPriceDRO.getDeposit()) && Objects.equals(1, productPriceDRO.getPayType());// 是否有预付金
		// 有价格，不是预付金，才使用优惠
		OrderDiscountCalcBO orderDiscountCalcBO = null;
		if (!isEarnestPrice && NumberUtil.isNotNullOrZero(payAmount)) {
			CalcAddOrderAmountDIO calcAddOrderAmountDIO = new CalcAddOrderAmountDIO();
			calcAddOrderAmountDIO.setInvoker(calcOrderAmountDIO.getInvoker());
			calcAddOrderAmountDIO.setDiscountItemCodes(calcOrderAmountDIO.getDiscountItemCodes());
			calcAddOrderAmountDIO.setPromId(calcOrderAmountDIO.getPromId());
			calcAddOrderAmountDIO.setOrderAmountDIO(OrderAmountDIO.builder().originalAmount(payAmount).build());
			DiscountConditionParamsDIO discountConditionParamsDIO = BeanMapper.map(calcOrderAmountDIO, DiscountConditionParamsDIO.class);
			discountConditionParamsDIO.setBizType(com.zmn.consts.GlobalConsts.BIZ_TYPE_C);
			discountConditionParamsDIO.setPlat(com.zmn.consts.GlobalConsts.PLAT_MARK_ZMN);
			discountConditionParamsDIO.setMember(GlobalConsts.NO);
			calcAddOrderAmountDIO.setDiscountConditionParamsDIO(discountConditionParamsDIO);
			orderDiscountCalcBO = orderDiscountCalcBService.calcAddOrderDiscount(calcAddOrderAmountDIO, null);

			if (orderDiscountCalcBO != null) {
				payAmount = MathUtil.sub(payAmount, orderDiscountCalcBO.getDiscountAmount());
				if (payAmount < 0) {
					logger.info("[{}] 优惠金额超出了支付金额处理", TAG);
					payAmount = 0;
					discountAmount = payAmount;
				} else {
					discountAmount = orderDiscountCalcBO.getDiscountAmount();
				}

				orderDiscountList = orderDiscountCalcBO.getOrderDiscountList();
				// 赋值优惠链list
				List<Set<PromBaseRuleDRO>> retLinkOfValidAll = orderDiscountCalcBO.getLinkOfValidAll();
				if (CollectionUtil.isNotNullOrEmpty(retLinkOfValidAll)) {
					for (Set<PromBaseRuleDRO> promBaseRuleDROS : retLinkOfValidAll) {
						Set<CalcOrderAmountPromBaseRuleDRO> newPromBaseRuleDROS = Sets.newHashSet();
						promBaseRuleDROS.forEach(s->
							newPromBaseRuleDROS.add(BeanMapper.map(s,CalcOrderAmountPromBaseRuleDRO.class))
						);
						linkOfValidAll.add(newPromBaseRuleDROS);
					}
				}
			}
		}

		// 预付方式,如果金额为空，则返回后支付
		Integer prepayType = Optional.ofNullable(productPriceDRO.getPayType()).orElse(2);
		if (NumberUtil.isNullOrZero(payAmount)) {
			prepayType = GlobalConsts.YES;
		}
		CalcOrderAmountDRO orderAmountByCalcDRO = new CalcOrderAmountDRO();
		orderAmountByCalcDRO.setHaveAmount(GlobalConsts.YES);
		orderAmountByCalcDRO.setOriginalAmount(productPriceDRO.getPrice());
		orderAmountByCalcDRO.setPayAmount(payAmount);
		orderAmountByCalcDRO.setDiscountAmount(discountAmount);
		orderAmountByCalcDRO.setAfterPromotionAmount(orderDiscountCalcBO != null ? orderDiscountCalcBO.getAfterPromotionAmount() : 0);
		orderAmountByCalcDRO.setPrepayType(prepayType);// 默认下单后支付
		orderAmountByCalcDRO.setFinalPrice(Objects.equals(productPriceDRO.getItemStandard(), GlobalConsts.YES) ? GlobalConsts.YES : GlobalConsts.NO);
		orderAmountByCalcDRO.setOrderServiceItemList(convertToServiceItemListDIO(productPriceDRO.getItemDRO(), number));
		orderAmountByCalcDRO.setOrderDiscountList(this.convertDiscountDOToDiscountDIO(orderDiscountList));
		orderAmountByCalcDRO.setLinkOfValidAll(linkOfValidAll);
		logger.info("[{}] 获取订单价格-返回：calcOrderAmount={}", TAG, orderAmountByCalcDRO);
		return ResponseDTO.success(orderAmountByCalcDRO);
	}

	private List<OrderDiscountDIO> convertToDiscountDIO(List<DiscountDTO> discountDTOS) {
		List<OrderDiscountDIO> list = Lists.newArrayList();
		if (CollectionUtil.isNullOrEmpty(discountDTOS)) {
			return list;
		}
		for (DiscountDTO discountDTO : discountDTOS) {
			OrderDiscountDIO orderDiscountDIO = new OrderDiscountDIO();
			orderDiscountDIO.setCateg(discountDTO.getDiscountCateg());
			orderDiscountDIO.setCategName(FicoConsts.getDiscountCategName(discountDTO.getDiscountCateg()));
			if (Objects.equals(discountDTO.getBatchId(), 10002)) {
				orderDiscountDIO.setType(OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE);
			} else {
				orderDiscountDIO.setType(discountDTO.getPreferentialType());
			}
			orderDiscountDIO.setAmount(discountDTO.getDiscountAmount());
			orderDiscountDIO.setTypeDesc("");
			orderDiscountDIO.setSourceId(discountDTO.getBatchId());
			orderDiscountDIO.setSourceData(discountDTO.getDiscountSourceData());
			orderDiscountDIO.setRemark(discountDTO.getItemCode());
			list.add(orderDiscountDIO);
		}
		return list;
	}

	private List<OrderDiscountDIO> convertDiscountDOToDiscountDIO(List<OrderDiscount> orderDiscounts) {
		List<OrderDiscountDIO> list = Lists.newArrayList();
		if (CollectionUtil.isNullOrEmpty(orderDiscounts)) {
			return list;
		}
		for (OrderDiscount discountDTO : orderDiscounts) {
			OrderDiscountDIO orderDiscountDIO = new OrderDiscountDIO();
			orderDiscountDIO.setCateg(discountDTO.getCateg());
			orderDiscountDIO.setCategName(discountDTO.getCategName());
			orderDiscountDIO.setType(discountDTO.getType());
			orderDiscountDIO.setItemId(discountDTO.getItemId());
			orderDiscountDIO.setItemCode(discountDTO.getItemCode());
/*			if (Objects.equals(discountDTO.getBatchId(), 10002)) {
				orderDiscountDIO.setType(OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE);
			} else {
				orderDiscountDIO.setType(discountDTO.getPreferentialType());
			}*/
			orderDiscountDIO.setAmount(discountDTO.getAmount());
			orderDiscountDIO.setTypeDesc("");
			orderDiscountDIO.setSourceId(discountDTO.getSourceId());
			orderDiscountDIO.setDmsDiscountId(discountDTO.getDmsDiscountId());
			orderDiscountDIO.setServiceId(discountDTO.getServiceId());
			list.add(orderDiscountDIO);
		}
		return list;
	}


	private List<OrderServiceItemDIO> convertToServiceItemListDIO(ItemDRO itemDRO, Integer number) {
		if (Objects.isNull(itemDRO)) {
			return null;
		}
		number = Optional.ofNullable(number).orElse(1);
		if (number > 1) {
			List<OrderServiceItemDIO> serviceItemList = new ArrayList<>();
			for (int i = 0; i < number; i++) {
				serviceItemList.add(convertToServiceItemDIO(itemDRO));
			}
			return serviceItemList;
		}
		return Lists.newArrayList(convertToServiceItemDIO(itemDRO));
	}


	private OrderServiceItemDIO convertToServiceItemDIO(ItemDRO itemDRO) {
		if (itemDRO == null) {
			return null;
		}
		OrderServiceItemDIO orderServiceItemDIO = new OrderServiceItemDIO();
		orderServiceItemDIO.setServItemId(itemDRO.getItemId());
		orderServiceItemDIO.setServItemName(itemDRO.getItemName());
		orderServiceItemDIO.setServItemGroupId(itemDRO.getItemTypeId());
		orderServiceItemDIO.setServItemGroupName(itemDRO.getItemTypeName());
		orderServiceItemDIO.setInternalSettlementPrice(itemDRO.getPriceInternalSettlement());
		orderServiceItemDIO.setExternalSettlementPrice(itemDRO.getPriceExternalSettlement());
		orderServiceItemDIO.setNumber(1);
		orderServiceItemDIO.setItemPrice(itemDRO.getPrice());
		return orderServiceItemDIO;
	}


	/**
	 * 新单
	 * @param newOrderDIO
	 * @return
	 */
	@Override
	public ResponseDTO<NewOrderDRO> addOrder(NewShopOrderDIO newOrderDIO) {
		logger.info("[{}] 添加店铺订单：NewShopOrderDIO={}", TAG, JSON.toJSONString(newOrderDIO));
		ValidateResult validateResult = ValidatorUtil.validator(newOrderDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseDTO.fail("提交参数错误：" + validateResult.toString());
		}
		if (StringUtils.isBlank(newOrderDIO.getOperator())) {
			newOrderDIO.setOperator("系统");
		}

		// DIO转换
		ZsNormalNewOrderDTO normalNewOrderDTO = BeanMapper.map(newOrderDIO, ZsNormalNewOrderDTO.class);
		normalNewOrderDTO.setReceiverManner(OrderConsts.RECEIVE_MANNER_MANUAL);
		normalNewOrderDTO.setUserType(UserConsts.USER_TYPE_ORDINARY);
		logger.info("未替换下单接口：[com.zmn.oms.dubbo.impl.zmn.shop.order.ShopOrderWorkRemoteServiceImpl.addOrder]，下单渠道：[{}]，下单方式：[{}]", normalNewOrderDTO.getChannelId(), normalNewOrderDTO.getReceiveEntranceId());
		return super.addOrder(normalNewOrderDTO);

	}

	/**
	 * 新增计价器订单
	 * @param newOrderDIO
	 * @return
	 */
	@Override
	public ResponseDTO<NewOrderDRO> addQuotationOrder(NewShopOrderDIO newOrderDIO) {

		logger.info("[{}] 添加计价器订单：NewShopOrderDIO={}", TAG, JSON.toJSONString(newOrderDIO));

		ValidateResult validateResult = ValidatorUtil.validator(newOrderDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseDTO.fail("提交参数错误：" + validateResult.toString());
		}
		if (StringUtils.isBlank(newOrderDIO.getOperator())) {
			newOrderDIO.setOperator("系统");
		}

		// DIO转换
		ZsNormalNewOrderDTO normalNewOrderDTO = BeanMapper.map(newOrderDIO, ZsNormalNewOrderDTO.class);
		normalNewOrderDTO.setReceiverManner(OrderConsts.RECEIVE_MANNER_MANUAL);
		normalNewOrderDTO.setServItemType(OrderConsts.SERVICE_ITEM_TYPE_FAULT);
		normalNewOrderDTO.setQuotationType(GlobalConsts.OPERATE_USER_TYPE_USER);
		logger.info("未替换下单接口：[com.zmn.oms.dubbo.impl.zmn.shop.order.ShopOrderWorkRemoteServiceImpl.addQuotationOrder]，下单渠道：[{}]，下单方式：[{}]", normalNewOrderDTO.getChannelId(), normalNewOrderDTO.getReceiveEntranceId());
		return super.addOrder(normalNewOrderDTO);
	}

	/**
	 * 修改计价器订单产品及服务项（仅用于修改【计价器类型】的订单产品）
	 * @param updateQuotationOrderProductDIO
	 * @return
	 */
	@Override
	public ResponseDTO<Boolean> updateQuotationOrderProduct(UpdateQuotationOrderProductDIO updateQuotationOrderProductDIO) {
		logger.info("[{}] 修改计价器订单产品：UpdateQuotationOrderProductDIO={}", TAG,
                JSON.toJSONString(updateQuotationOrderProductDIO));

		ValidateResult validateResult = ValidatorUtil.validator(updateQuotationOrderProductDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseDTO.fail("提交参数错误：" + validateResult.toString());
		}

		OperatePermissionVO operatePermission = orderWorkOperatePermissionBService
				.getOperatePermission(updateQuotationOrderProductDIO.getOrderId(), updateQuotationOrderProductDIO.getWorkId(), OrderConsts.ORDER_OP_TYPE_MODIFY_PRODUCT);
		if (!operatePermission.getCanOperate()) {
			return ResponseDTO.fail(operatePermission.getMsg());
		}

		if (Objects.equals(GlobalConsts.OPERATE_USER_TYPE_USER, updateQuotationOrderProductDIO.getOperatorType())) {
			updateQuotationOrderProductDIO.setOperator("用户");
		}
		String operator = updateQuotationOrderProductDIO.getOperator();
		if (StringUtils.isBlank(operator)) {
			updateQuotationOrderProductDIO.setOperator("系统");
		}
		else if (operator.length() > 32) {
			updateQuotationOrderProductDIO.setOperator(operator.substring(0, 32));
		}

		OrderWork orderWork = orderWorkService.findOrderWorkByKey(updateQuotationOrderProductDIO.getOrderId(), updateQuotationOrderProductDIO.getWorkId());
		List<Integer> serviceItemTypeList = Lists.newArrayList(OrderConsts.SERVICE_ITEM_TYPE_ADVANCE_PAY, OrderConsts.SERVICE_ITEM_TYPE_FAULT);
		if (!serviceItemTypeList.contains(orderWork.getServItemType())) {
			return ResponseDTO.fail("价格类型有变化，请联系师傅操作！");
		}

		ModifyQuotationDTO modifyQuotationDTO = BeanMapper.map(updateQuotationOrderProductDIO, ModifyQuotationDTO.class);
		modifyQuotationDTO.setServItemType(OrderConsts.SERVICE_ITEM_TYPE_FAULT);
		modifyQuotationDTO.setQuotationType(updateQuotationOrderProductDIO.getOperatorType());
		modifyQuotationDTO.setOperator(updateQuotationOrderProductDIO.getOperator());
		modifyQuotationDTO.setTariffType(orderWork.getServItemType());
		ResponseDTO<Boolean> oldResponse = super.updateOrderProduct(modifyQuotationDTO);

		if (NumberUtil.isNotNullOrZero(updateQuotationOrderProductDIO.getUserId()) || NumberUtil.isNotNullOrZero(updateQuotationOrderProductDIO.getOperatorId())) {
			// 保存报价结束日志
			OrderQuotationLog log = new OrderQuotationLog();
			log.setOrderId(updateQuotationOrderProductDIO.getOrderId());
			log.setWorkId(updateQuotationOrderProductDIO.getWorkId());
			log.setOperatorType(updateQuotationOrderProductDIO.getOperatorType());
			log.setUserId(updateQuotationOrderProductDIO.getOperatorId());
			log.setType(OrderConsts.QUOTATION_END);
			orderQuotationLogBService.saveLogWithOrderLog(log);
		}

		if (oldResponse.isSuccess() && oldResponse.getData() != null) {
			return ResponseDTO.success(oldResponse.getData(), oldResponse.getMessage());
		}
		else {
			if (oldResponse.getStatus() > OmsErrorCodeConsts.MIN_CODE) {
				return ResponseDTO.fromErrorCodeTable(oldResponse.getStatus());
			} else {
				return ResponseDTO.fail(oldResponse.getMessage());
			}
		}
	}

	/**
	 * 取消订单
	 *
	 * @param cancelOrderDIO
	 * @return
	 */
	@Override
	public ResponseDTO cancelOrder(CancelOrderDIO cancelOrderDIO) {
		logger.info("[{}] 取消店铺订单：CancelOrderDIO={}", TAG, JSON.toJSONString(cancelOrderDIO));

		ValidateResult validateResult = ValidatorUtil.validator(cancelOrderDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseDTO.fail("提交参数错误");
		}

		cancelOrderDIO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_USER);
		return super.cancelOrder(cancelOrderDIO);
	}
}
